<template>
    <div>
        <el-upload
            accept=".xlsx, .xls"
            :file-list="fileList"
            :action="actionUrl"
            :before-upload="beforeUploadFile"
            :on-exceed="exceedFile"
            :on-success="uploadSuccess"
            :show-file-list="isShowFile"
            multiple
            :limit="limitNum"
        >
            <el-button type="primary" style="margin-left:0px" size="mini">
                导入Excel
            </el-button>
        </el-upload>
        <div class="el-upload__tip">只以上传文件格式为： {{ tip }}</div>
    </div>
</template>
<script>
export default {
    props: {
        tip: {
            type: String,
            default: '.xlsx, .xls'
        }
    },
    data() {
        return {
            fileList: [], //excel 文件列表
            limitNum: 3, //选择文件个数
            actionUrl: 'http://test.zhenpin.com/pms/platformshelfsku/importplatformshelfsku.json', //上传文件url
            isShowFile: true //文件列表是否显示 默认不显示
        }
    },
    methods: {
        //文件上传之前的钩子
        beforeUploadFile(file) {
            console.log('before upload')
            console.log(file.size)
            var FileExt = file.name.replace(/.+\./, '')
            if (['xls', 'xlsx'].indexOf(FileExt.toLowerCase()) === -1) {
                this.$message({
                    type: 'warning',
                    message: '请上传后缀名为xls、xlsx的附件！'
                })
                return false
            }
            //file.size 以字节为单位
            this.isLt2k = file.size / 2048 < 100 ? '1' : '0'
            if (this.isLt2k === '0') {
                this.$message({
                    message: '上传文件大小不能超过100k!',
                    type: 'error'
                })
            }
            return this.isLt2k === '1' ? true : false
        },
        //文件超出个数时的钩子
        exceedFile(files, fileList) {
            console.log('文件超出个数：', files)
            this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`)
        },
        exportErrorFile() {},
        //文件上传成功时的钩子
        uploadSuccess(response, file, fileList) {
            console.log('上传文件', response.data)
            console.log('返回状态', response.code)
            console.log(fileList)
            if (response.code != '0000') {
                this.excelData = response.data
                this.exportErrorFile()
                return this.$message.error('导入失败！')
            } else {
                this.isShowFile = true
                return this.$message.success('导入成功！')
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.el-upload__tip {
    max-width: 300px;
    margin: 0 auto;
    padding-top: 10px;
}
</style>
